
angular.module('scanPrint.controllers', [])

    .controller('HomeCtrl', ['$scope',  '$ionicModal', '$ionicLoading','$cordovaToast','HomeService',
        function ($scope ,$ionicModal ,$ionicLoading ,$cordovaToast,HomeService) {

            $scope.data = {
                name:"",
                userImage:"img/default-avatar.png",
                car:"",
                wish:"",
                position:"",
                pairedDevices:[],
                selectDevice:""
            };
            var orderNo = '';//订单号
            var orderDate = '';//下单时间
            var orderId = '';//订单id

            //芯片数据：芯片ID,废品订单标识,订单ID,喷码内容,取货口,用户名称
            var chipData = "31 32 33 34 35 36 7C 30 7C 31 36 30 37 32 30 30 30 30 30 38 7C";
            // var chipData = "123456789|0|16072000008|XXXXXX|北京|张三";
            
            $ionicModal.fromTemplateUrl('tpls/setting.html', {
                scope: $scope,
                animation: 'slide-in-right'
            }).then(function(modal) {
                $scope.modal = modal;
            });

            

            function getOrderData(orderId){
                $ionicLoading.show({
                    template: 'Loading...'
                });
                
                HomeService.getOrderData(orderId).then(function(data){
                  $ionicLoading.hide();
                  
                  $scope.data.name = data.data.user_nickname;
                  $scope.data.car = data.data.product_name;
                  $scope.data.wish = data.data.hand_text;
                  $scope.data.position = data.data.address_name;
                  $scope.data.userImage = data.data.user_avatar;
                  orderNo = data.data.docno;
                  orderDate = data.data.order_date;
                },function(error){
                  $ionicLoading.hide();
                  $cordovaToast.showShortBottom(error);
                   
                });
            }
              
            //获取芯片数据
            function getChipData(data){
                var chip_data = data.split("7C");
                // $scope.data.chipId = chip_data[0];
                // var orderId = parseInt(chip_data[2]);
                var order_data = chip_data[2].split(" ");
                var order_id = '';
                for (var i = 1; i < order_data.length-1; i++) {
                     order_id = order_id + String.fromCharCode(parseInt(order_data[i],16));
                }

                getOrderData(order_id);
                   
            }   

            // getChipData(chipData);

            
            document.addEventListener("deviceready", function() {

              $scope.$on('rfiduhf.DataReceived', function (e, data) {
                 $cordovaToast.showShortBottom(data);
                 getChipData(data);
              });
              $scope.$on('bluetoothprint.DataReceived', function (e, data) {
                 
                 $scope.data.pairedDevices = [];
                 var dataArray = data.split(",");
                 for (var i = 0; i < dataArray.length-1; i++) {
                     var str = dataArray[i];
                     var name = str.substring(0,str.indexOf("&"));
                     var address = str.substring(str.indexOf("&")+1);
                     $scope.data.pairedDevices.push({
                         name:name,
                         address:address
                     });
                 }
                 
                 $scope.modal.show().then(function () {
                      // $scope.$apply();
                  });
 
              });

              $scope.$on('bluetoothprint.StatusReceived', function (e, data) {
                  
                 
                 if(data==="5"){
                   window.localStorage.setItem("gprinter", angular.toJson($scope.data.selectDevice));
                   $cordovaToast.showShortBottom('连接成功');
                   $ionicLoading.hide();
                 }
                 // if(data==="0"){
                 //   alert("断开成功");
                 // }
 
              });

              $scope.$on('$ionicView.afterLeave', function () {
                 closeRfidUhf();
                 closeGPrintConnect();
              });

              initMoto();//初始化Motorola的扫码插件
              //如果有打印机地址，连接打印机
              var gprinter_address = angular.fromJson(window.localStorage.getItem("gprinter"))+"";
              
              if(gprinter_address!=null&&gprinter_address!==""){
                 connectGPrint(gprinter_address);
              }
              //打开高频扫描
              openRfidUhf();

            }, false);

             $scope.getOneDevice = function(address){

                $scope.data.selectDevice = address;  
                $scope.modal.hide();
                
              };

              $scope.getPairedDevices = function(){
                if (window.cordova && cordova.plugins.BluetoothPrint) {
                    
                    cordova.plugins.BluetoothPrint.getPairedDevices(function () {
                
                    }, function () {
                    });
                } 
                // $scope.data.pairedDevices = [];
                // var data = "123&1c:2b,456&2c:3b,";
                //  var dataArray = data.split(",");
                //  for (var i = 0; i < dataArray.length-1; i++) {
                //      var str = dataArray[i];
                //      var name = str.substring(0,str.indexOf("&"));
                //      var address = str.substring(str.indexOf("&")+1);
                //      $scope.data.pairedDevices.push({
                //          name:name,
                //          address:address
                //      });
                //  }
                //  $scope.modal.show().then(function () {
                //       // $scope.$apply();
                //  });
            };
            $scope.print = function(){
                $ionicLoading.show({
                    template: 'Loading...'
                });
                HomeService.updateOrderStatus(orderId,10).then(function(data){
                    $ionicLoading.hide();
                    if(data){
                       $cordovaToast.showShortBottom("更新订单状态成功");
                    }
                    else{
                       $cordovaToast.showShortBottom("更新订单状态失败");
                    }
                     
                },function(error){
                    $ionicLoading.hide();
                    $cordovaToast.showShortBottom(error);
                });
                cordova.plugins.BluetoothPrint.printText($scope.data.name,
                  $scope.data.car,$scope.data.wish,$scope.data.position,orderNo,orderDate, function (success) {
               
                }, function (error) {
                   $cordovaToast.showShortBottom(error);
                });
            };
            $scope.connect = function(){
                connectGPrint($scope.data.selectDevice);
            };
            //连接打印机蓝牙(蓝牙地址)
            function connectGPrint(address){
                // alert(address);
                if(address!=null&&address!==""&&address!=="null"){
                  $ionicLoading.show({
                    template: 'Loading...'
                  });
                  if (window.cordova && cordova.plugins.BluetoothPrint) {

                      cordova.plugins.BluetoothPrint.connectDevice(address, function (success) {
                     
                      }, function (error) {
                         $cordovaToast.showShortBottom(error);
                      });
                  } 
                }
                
                
            }
            //关闭打印机连接
            function closeGPrintConnect(){
                if (window.cordova && cordova.plugins.BluetoothPrint) {
                    cordova.plugins.BluetoothPrint.closeConnect();
                } 
            }
            //关闭高频扫描  
            function closeRfidUhf(){
                if (window.cordova && cordova.plugins.RfidUhf) {
                    cordova.plugins.RfidUhf.close();
                }   
            }
            //打开高频扫描
            function openRfidUhf(){
                if (window.cordova && cordova.plugins.RfidUhf) {
                    cordova.plugins.RfidUhf.open(function () {
                    }, function () {
                    });
                }   
            }

            $scope.openScan = function(){
                openRfidUhf();
            };
            $scope.closeScan = function(){
                closeRfidUhf();
                
            };
            
            // $scope.startScan = function() {    
            //    if (window.datawedge) {
            //        window.datawedge.startScanner();
            //    }
            // };

            function initMoto() {
                
                if (window.datawedge) {
                    
                  window.datawedge.registerForBarcode(function(data) {
                    
                    var labelType = data.type,
                      barcode = data.barcode;
                      $scope.data.name = "吴少华";
                      $scope.data.car = "吉普车";
                      $scope.data.wish = "亲亲我的宝贝";
                      $scope.data.position = "广州";
                      $scope.$apply();
                    
                  });
                  window.datawedge.registerForMagstripe(function(tracks) {
                    var track1, track2;
                    if (tracks[0]) {
                      track1 = tracks[0].split('^');
                      var cc = {
                        number: track1[0].substr(2),
                        name: track1[1].trim(),
                        expr: '20' + track1[2].substr(0, 2) + '-' + track1[2].substr(2, 2)
                      };
                    } else if (tracks[1]) {
                      track2 = tracks[1];
                    } else {}

                  });
                }
            }
       
        }
    ]);